﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;

namespace PloobsEngine.SceneControl
{
    public class IntermediateTexture
    {
        public RenderTarget2D RenderTarget;
        public bool InUse;
    }


    public class TexturesPool
    {
        private static List<IntermediateTexture> intermediateTextures = new List<IntermediateTexture>();


        public IntermediateTexture GetIntermediateTexture(int width, int height, SurfaceFormat format)
        {
            return GetIntermediateTexture(width, height, format, MultiSampleType.None, 0);
        }

        public IntermediateTexture GetIntermediateTexture(int width, int height, SurfaceFormat format, MultiSampleType msType, int msQuality)
        {
            // Look for a matching rendertarget in the cache
            for (int i = 0; i < intermediateTextures.Count; i++)
            {
                if (intermediateTextures[i].InUse == false
                    && height == intermediateTextures[i].RenderTarget.Height
                    && format == intermediateTextures[i].RenderTarget.Format
                    && width == intermediateTextures[i].RenderTarget.Width
                    && msType == intermediateTextures[i].RenderTarget.MultiSampleType
                    && msQuality == intermediateTextures[i].RenderTarget.MultiSampleQuality)
                {
                    intermediateTextures[i].InUse = true;
                    return intermediateTextures[i];
                }
            }

            // We didn't find one, let's make one
            IntermediateTexture newTexture = new IntermediateTexture();
            newTexture.RenderTarget = new RenderTarget2D(EngineStuff.GraphicsDevice,
                                                            width,
                                                            height,
                                                            0,
                                                            format,
                                                            msType,
                                                            msQuality,
                                                            RenderTargetUsage.PreserveContents);
            intermediateTextures.Add(newTexture);
            newTexture.InUse = true;
            return newTexture;
        }

    }

}
